from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template
from django.http import HttpResponse, Http404
from django.contrib.auth.models import User
from django.template import RequestContext
from django.http import HttpResponseRedirect
#from django.contrib.auth.views import login
from django.contrib.auth import login
from django.contrib.auth import logout
from django.shortcuts import render_to_response
from forfood.restaurant.models import *
from forfood.main.forms import *
from forfood.helpers.user_helper import *

def main_page(request):
    restaurant_list = Restaurant.objects.order_by('-last_update')
    customer = find_customer(request.user)
    restaurant = find_restaurant(request.user)
    
    for r in restaurant_list:
        r.is_loved_by(customer)
    
    return render_to_response(
        'main/main.html', RequestContext(request, locals())
    )

def login_page(request):
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            user = form.get_user()
            login(request, user)

            if request.session.test_cookie_worked():
                request.session.delete_test_cookie()
            
            if find_restaurant(request.user):
                return HttpResponseRedirect('/restaurant_manage/')
            
            return HttpResponseRedirect('/')
    else:
        form = LoginForm()
    return render_to_response(
        "registration/login.html", 
        RequestContext(request,{'form': form})
    )

def logout_page(request):
    logout(request)
    return HttpResponseRedirect('/')
def register_page(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)
        if form.is_valid():
            new_user = form.save()
            return HttpResponseRedirect('/login')
    else:
        form = RegistrationForm()
    return render_to_response(
        "registration/register.html", 
        RequestContext(request,{'form': form})
    )
